package com.lzp.wechat.common.task;

import com.alibaba.fastjson.JSONObject;
import com.lzp.wechat.common.constants.RedisConstants;
import com.lzp.wechat.common.utils.RedisCacheUtils;
import com.lzp.wechat.entity.AccessToken;
import com.lzp.wechat.service.AccessTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@EnableScheduling
public class AccessTokenTask {

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private RedisCacheUtils redisCacheUtils;

    /**
     * access_token 是公众的全局唯一调用凭据
     * access_token 的有效期为 2 个小时，需要定时刷新 access_token，重复获取会导致之前一次获取的失效
     * 延迟一秒执行，每7000秒刷新一次
     * access_token存入redis
     */
    @Scheduled(initialDelay = 1000, fixedDelay = 7000 * 1000)
    public void getAccessToken() {
        String result = accessTokenService.getAccessToken();
        AccessToken accessToken = JSONObject.parseObject(result, AccessToken.class);
        String access_token = accessToken.getAccess_token();
        redisCacheUtils.set(RedisConstants.ACCESS_TOKEN, access_token);
        log.info("微信access_token保存成功：{}", access_token);
    }

}
